package cn.nexd.app.indoor.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.support.v7.widget.AppCompatEditText;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import app.xu.com.listtext.listener.OnTextItemClickListener;
import app.xu.com.listtext.view.ListTextView;
import butterknife.Bind;
import butterknife.OnClick;
import cn.nexd.app.indoor.R;
import cn.nexd.app.indoor.adapter.GridViewAdapter;
import cn.nexd.app.indoor.adapter.SearchResultAdapter;
import cn.nexd.app.indoor.application.MyApplication;
import cn.nexd.app.indoor.model.FloorModel;
import cn.nexd.app.indoor.model.GridViewModel;
import cn.nexd.app.indoor.model.MallModel;
import cn.nexd.app.indoor.model.RecordBean;
import cn.nexd.app.indoor.overyly.CompassOverlay;
import cn.nexd.app.indoor.overyly.HighLightOverlay;
import cn.nexd.app.indoor.overyly.MarkerOverlay;
import cn.nexd.app.indoor.overyly.MorePointOverly;
import cn.nexd.app.indoor.presenter.NexdMapPresenter;
import cn.nexd.app.indoor.ui.iView.INexdMapActivityView;
import cn.nexd.app.indoor.ui.view.MyScrollView;
import cn.nexd.app.indoor.util.ProgressDialogUtils;
import cn.nexd.app.indoor.util.SharedPreferencesUtil;
import cn.nexd.map.rendering.POIData;
import cn.nexd.map.rendering.SVGMapViewClickListener;
import cn.nexd.map.rendering.SVGMapViewListener;
import cn.nexd.map.rendering.SVGMapViewOtherClickListener;
import cn.nexd.map.rendering.core.SVGMapBaseOverlay;
import cn.nexd.map.rendering.core.componet.SVGMapView;
import cn.nexd.map.rendering.core.componet.data.Feature;

/**
 * 用来展示 Nexd Map 的activity, 并实时显示定位结果, 路径规划
 * <p/>
 * Created by wangxu on 16/7/20.
 */
public class NexdMapActivity extends BaseActivity<NexdMapPresenter> implements INexdMapActivityView, SVGMapViewClickListener, OnTextItemClickListener, SVGMapViewListener, SVGMapViewOtherClickListener {
    private static final String TAG = "NexdMapActivity";

    public static final int MARK_TYPE_LOCATION = 0;
    public static final int MARK_TYPE_MARKER = 1;
    public static final int MARK_TYPE_ROUTE_PLAN = 2;
    public static boolean IS_LOCATIONING = false;

    @Bind(R.id.svg_map)
    SVGMapView nexdMap;
    @Bind(R.id.type_record)
    MyScrollView typeRecord;
    @Bind(R.id.back)
    ImageButton back;
    @Bind(R.id.gotothere)
    Button goToThere;
    @Bind(R.id.start_position)
    Button startPosition;
    @Bind(R.id.end_position)
    Button endPosition;
    @Bind(R.id.poi_name)
    TextView poiName;
    @Bind(R.id.popuLayout)
    FrameLayout popuLayout;
    @Bind(R.id.search_layout)
    FrameLayout searchLayout;
    @Bind(R.id.map_layout)
    RelativeLayout mapLayout;
    @Bind(R.id.search_content)
    AppCompatEditText searchContent;
    @Bind(R.id.search_clear)
    ImageButton searchClear;
    @Bind(R.id.search_go)
    ImageView searchGoBtn;
    @Bind(R.id.ltv_navigate)
    ListTextView ltvNavigate;
    @Bind(R.id.gridview)
    GridView gridview;
    @Bind(R.id.tlv_record)
    ListView tlvRecoed;
    @Bind(R.id.search_result)
    ListView searchResult;
    @Bind(R.id.map_top_layout)
    View mapTopLayout;
    @Bind(R.id.maplayout_search)
    ImageView topSearchBtn;
    @Bind(R.id.maplayout_home)
    ImageView topHomeBtn;
    @Bind(R.id.maplayout_title)
    TextView topTitle;


    private boolean isEndPositionEnadle = false;
    private MarkerOverlay markerOverlay;
    private List<FloorModel> floorModels;
    private List<String> itemNames;
    private GridViewAdapter adapter;
    private List<RecordBean> searchRecords;
    private POIData startPoiData;
    private POIData endPoiData;
    private SearchResultAdapter searchResultAdapter;
    private List<Feature> features;
    private MallModel mallModel;
    private InputMethodManager imm;
    private boolean search = false;
    private int backFlag = 0;

    private CompassOverlay compassOverlay;
    private HighLightOverlay highLightOverlay;

    @Override
    public int getLayoutRes() {
        return R.layout.activity_map_show;
    }

    @Override
    public void initPresenter() {
        presenter = new NexdMapPresenter(this, this);
        presenter.init();
    }

    @Override
    public void initView() {
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //添加消息处理
        Intent intent = getIntent();
        mallModel = intent.getParcelableExtra("MallModel");
        floorModels = intent.getParcelableArrayListExtra("FloorModels");

        //2016.3.21 xun 设置头布局数据及监听事件
        initTopLayout();
        // 从本地获取搜索记录,显示在历史搜索记录中
        searchRecords = SharedPreferencesUtil.getSearchRecord(this);
        // 设置按类型搜索的9宫格内容
        adapter = new GridViewAdapter(this, initData());
        //从SharedPrefrences查询结果
        tlvRecoed.setAdapter(new SearchRecordAdapter());
        gridview.setAdapter(this.adapter);
        features = new ArrayList<>();

        ltvNavigate.setOnTextItemClickListener(this);
        searchResultAdapter = new SearchResultAdapter(this);
        searchResult.setAdapter(searchResultAdapter);
        // 实例化业务接口
        presenter.setNexdMap(nexdMap);
        presenter.setMallModel(mallModel);
        ltvNavigate.setItems(presenter.initARItem(floorModels));
        ltvNavigate.setSelection(ListTextView.DEFAULT_SELECTED_ITEM);
        // 初始化地图
        presenter.initLocation();
        nexdMap.registerMapViewClickListener(this);
        nexdMap.registerMapViewListener(this);
        nexdMap.registerMapViewOtherClickListener(this);
        // 初始化加载第一张地图
        if (floorModels != null && floorModels.size() != 0) {
            ProgressDialogUtils.showProgressDialog(this, "地图加载中...", "", true);
            presenter.loadMap(floorModels.get(0));
        } else {
            showToast("获取楼层信息出错！");
        }
    }

    private void initTopLayout() {
        if (mapTopLayout.getVisibility() == View.GONE) {
            mapTopLayout.setVisibility(View.VISIBLE);
        }
        topTitle.setText(mallModel.getMallCName());
        if (!MyApplication.IS_ROUTE_PLAN) {
            startPosition.setVisibility(View.GONE);
            endPosition.setVisibility(View.GONE);
            topSearchBtn.setVisibility(View.GONE);
        }
    }


    @OnClick({R.id.maplayout_back, R.id.back, R.id.maplayout_search, R.id.maplayout_home, R.id.search_go, R.id.search_clear, R.id.gotothere, R.id.start_position, R.id.end_position/*, R.id.point_direction*/})
    public void onBtnClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                if (searchResultAdapter.getCount() != 0) {
                    typeRecord.setVisibility(View.VISIBLE);
                    searchResult.setVisibility(View.GONE);
                    searchResultAdapter.clear();
                } else {
                    mapTopLayout.setVisibility(View.VISIBLE);
                    searchLayout.setVisibility(View.GONE);
                    mapLayout.setVisibility(View.VISIBLE);
                }
                popuLayout.setVisibility(View.VISIBLE);
                imm.hideSoftInputFromWindow(back.getWindowToken(), 0);
                break;
            case R.id.maplayout_back:
                Intent intent = new Intent(this, MallListActivity.class);
                startActivity(intent);
                break;
            case R.id.search_go:
                if (searchResultAdapter.getCount() == 0) {
                    Toast.makeText(this, "墨墨没有找到您想要去的小店~", Toast.LENGTH_SHORT).show();
                    return;
                }
                search = true;
                imm.hideSoftInputFromWindow(back.getWindowToken(), 0);
                nexdMap.removeOverlay(MARK_TYPE_MARKER);
                searchLayout.setVisibility(View.GONE);
                popuLayout.setVisibility(View.GONE);
                mapTopLayout.setVisibility(View.VISIBLE);
                mapLayout.setVisibility(View.VISIBLE);
                addNexdMarkers(searchResultAdapter.getPointF(), R.drawable.icon_marker, MARK_TYPE_MARKER);
                break;
            case R.id.maplayout_search:
                backFlag = 0;
                mapTopLayout.setVisibility(View.GONE);
                if (searchResultAdapter.getCount() != 0) {
                    typeRecord.setVisibility(View.GONE);
                    searchResult.setVisibility(View.VISIBLE);
                    searchResultAdapter.notifyDataSetChanged();
                }
                searchLayout.setVisibility(View.VISIBLE);
                mapLayout.setVisibility(View.GONE);
                popuLayout.setVisibility(View.GONE);
                break;
            case R.id.maplayout_home:
                startActivity(new Intent(this, AboutmeActivity.class));
                break;
            case R.id.search_clear:
                searchContent.setText("");
                break;
            case R.id.gotothere:
                if (startPoiData == null) {

                    if (endPoiData != null && IS_LOCATIONING) {
                        nexdMap.removeOverlay(MARK_TYPE_MARKER);
                        if (presenter.routePlanXY2POI(endPoiData)) {
                            popuLayout.setVisibility(View.GONE);
                            search = false;
                        } else {
                            startPosition.setVisibility(View.VISIBLE);
                            endPosition.setVisibility(View.VISIBLE);
                            goToThere.setVisibility(View.GONE);
                            isEndPositionEnadle = false;
                        }
                    } else {
                        showToast("定位中...");
                    }
                } else {
                    nexdMap.removeOverlay(MARK_TYPE_MARKER);
                    if (presenter.routePlanPOI2POI(startPoiData, endPoiData)) {
                        popuLayout.setVisibility(View.GONE);
                        search = false;
                    } else {
                        startPosition.setVisibility(View.VISIBLE);
                        endPosition.setVisibility(View.VISIBLE);
                        goToThere.setVisibility(View.GONE);
                        isEndPositionEnadle = false;
                    }
                }
                break;

            case R.id.start_position:
                startPoiData = endPoiData;
                startPosition.setVisibility(View.GONE);
                popuLayout.setVisibility(View.GONE);
                break;

            case R.id.end_position:
                isEndPositionEnadle = true;
                startPosition.setVisibility(View.GONE);
                endPosition.setVisibility(View.GONE);
                goToThere.setVisibility(View.VISIBLE);
                break;
//            case R.id.point_direction:
//                nexdMap.setCurrentRotationDegrees(0, 0, 0);
//                break;

        }

    }


    // 向地图添加一堆Mark
    private void addNexdMarkers(List<PointF> pointFs, int res, int type) {
        MorePointOverly morePointOverly = new MorePointOverly(this);
        morePointOverly.setRes(res);
        morePointOverly.setPositions(pointFs);
        nexdMap.addOverlay(morePointOverly, type);
    }

    // 初始化九宫格内容
    private ArrayList<GridViewModel> initData() {
        ArrayList<GridViewModel> gridViewModels = new ArrayList<>();
        gridViewModels.add(new GridViewModel(R.drawable.mark_type_selected_clothing, "服装", "101510"));
        gridViewModels.add(new GridViewModel(R.drawable.mark_type_selected_food, "美食", "101010"));
        gridViewModels.add(new GridViewModel(R.drawable.shopping, "超市", "102210"));
        gridViewModels.add(new GridViewModel(R.drawable.mark_type_selected_coffee, "咖啡", "101014"));
        gridViewModels.add(new GridViewModel(R.drawable.mark_type_selected_ktv, "KTV", "101111"));
        gridViewModels.add(new GridViewModel(R.drawable.mark_type_selected_movies, "影院", "101112"));
        gridViewModels.add(new GridViewModel(R.drawable.mark_type_selected_parking, "停车场", "102513"));
        gridViewModels.add(new GridViewModel(R.drawable.toilet, "卫生间", "102515"));
        return gridViewModels;
    }


    /**
     * 楼层 item 的点击事件
     *
     * @param which 点击在列表上的索引值
     * @param name  当前索引的名字
     */
    @Override
    public void onItemClickListener(int which, String name) {
        Log.d(TAG, "onItemClickListener: 切换楼层 :  " + name);
        ProgressDialogUtils.showProgressDialog(this, "切换中...", "", true);
        presenter.stopLocation();
        presenter.setCurrentFloor(floorModels.get(which));
    }


    @Override
    protected void onDestroy() {
        if (nexdMap != null) {
            nexdMap.destroyDrawingCache();
        }
//        presenter.destory();
        super.onDestroy();
    }

    // 应用stop 停止采集定位
    @Override
    protected void onStop() {
        presenter.stopLocation();
        super.onStop();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        presenter.startLocation();
    }

    /**
     * 地图poi的点击事件
     *
     * @param v
     * @param v1
     * @param v2
     * @param v3
     * @param poiData
     */
    @Override
    public void onClick(float v, float v1, float v2, float v3, POIData poiData) {
        if (isEndPositionEnadle) {
            return;
        }
        if (!search) {
            nexdMap.removeOverlay(MARK_TYPE_MARKER);
            nexdMap.removeOverlay(MARK_TYPE_ROUTE_PLAN);
            addNexdMarker(new PointF(poiData.getCenter_x(), poiData.getCenter_y()), R.drawable.icon_marker, MARK_TYPE_MARKER);
        }
        popuLayout.setVisibility(View.VISIBLE);
        poiName.setText(poiData.getName());
        this.endPoiData = poiData;
    }

    // 向地图添加一个mark
    private void addNexdMarker(PointF pointF, int res, int type) {
        if (markerOverlay == null) {
            markerOverlay = new MarkerOverlay(this);
        }
        markerOverlay.setPosition(pointF);
        markerOverlay.setRes(res);
        nexdMap.addOverlay(markerOverlay, type);
    }

    /**
     * 地图加载完成的监听事件
     *
     * @param taskId
     * @param buildName
     */
    @Override
    public void onMapLoadComplete(long taskId, String buildName) {
        Log.d(TAG, "onMapLoadComplete: map load complete");
        if (nexdMap.isMapLoadFinsh()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ProgressDialogUtils.dismissProgressDialog(NexdMapActivity.this);
                    Log.d("MySvgMapViewListener", "地图加载完成");
                    presenter.startLocation();
                }
            });

            // 跑马灯效果

            List<Integer> indexs = new ArrayList<>();
            List<Feature> features = new ArrayList<>();
            while (true) {
                if (indexs.size() != 0) {
                    indexs.clear();
                    features.clear();
                } else {
                    nexdMap.getFloorFeature().getFeatures().remove(0);
                    while (true) {
                        Random r = new Random();
                        int index = r.nextInt(nexdMap.getFloorFeature().getFeatures().size() - 1);
                        if (!indexs.contains(index)) {
                            indexs.add(index);

                            Map<Long, Feature> longFeatureMap = nexdMap.getFloorFeature().getFeatures().get(index);
                            for (Map.Entry entry : longFeatureMap.entrySet()) {
                                features.add((Feature) entry.getValue());
                            }
                        }
                        if (indexs.size() == 1) {
                            break;
                        }
                    }
                    if (highLightOverlay == null) {
                        highLightOverlay = new HighLightOverlay(features);
                        nexdMap.addOverlay(highLightOverlay, MARK_TYPE_MARKER);
                    } else {
                        highLightOverlay.resetFeature(features);
                        nexdMap.refresh();
                    }

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }

        } else {
            Log.d("MySvgMapViewListener", "加载未完成");
        }
    }


    /**
     * 地图加载失败的监听事件
     */
    @Override
    public void onMapLoadError() {
        showToast("地图加载失败，请检查您的数据!");
    }

    /**
     * 获取当前地图的 bitmap 对象
     *
     * @param bitmap
     */
    @Override
    public void onGetCurrentMap(Bitmap bitmap) {
        presenter.saveNexdMap(bitmap);
    }

    /**
     * 地图的非 POI  区域的点击事件
     *
     * @param v
     * @param v1
     * @param v2
     * @param v3
     */
    @Override
    public void onClick(float v, float v1, float v2, float v3) {
        if (!isEndPositionEnadle) {
            popuLayout.setVisibility(View.GONE);
            nexdMap.removeOverlay(MARK_TYPE_MARKER);
            nexdMap.removeOverlay(MARK_TYPE_ROUTE_PLAN);
        }
    }

    /**
     * 加载地图
     *
     * @param svgPath
     */
    @Override
    public void loadMap(String svgPath) {
        try {
            nexdMap.loadMap(new FileInputStream(new File(svgPath)));
        } catch (Exception e) {
            MyApplication.getInstance().reportException(e);
        }
    }

    /**
     * 切换楼层
     *
     * @param svgPath
     */
    @Override
    public void setCurrentFloor(String svgPath) {
        try {
            searchContent.setText("");
            nexdMap.setCurrentFloor(new FileInputStream(new File(svgPath)), this);
            nexdMap.registerMapViewClickListener(this);
            popuLayout.setVisibility(View.GONE);
        } catch (FileNotFoundException e) {
            MyApplication.getInstance().reportException(e);
        }
    }

    /**
     * 添加涂层
     *
     * @param baseOverlay
     * @param type
     */
    @Override
    public void addOverlay(SVGMapBaseOverlay baseOverlay, int type) {
        nexdMap.addOverlay(baseOverlay, type);
    }

    /**
     * reset 路径规划数据
     */
    @Override
    public void resetRoutePlan() {
        isEndPositionEnadle = false;
        startPoiData = null;
        endPoiData = null;
        startPosition.setVisibility(View.VISIBLE);
        endPosition.setVisibility(View.VISIBLE);
        goToThere.setVisibility(View.GONE);
    }

    static class ViewHolder {
        TextView textView;
    }

    private class SearchRecordAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return searchRecords.size();
        }

        @Override
        public RecordBean getItem(int position) {
            return searchRecords.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;

            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = FrameLayout.inflate(NexdMapActivity.this, android.R.layout.simple_dropdown_item_1line, null);
                viewHolder.textView = (TextView) convertView.findViewById(android.R.id.text1);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.textView.setText(getItem(position).getRecord());
            return convertView;
        }
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(NexdMapActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}
